import { setToken, removeToken } from '../../utils/auth';
import { login, getInfo } from '../../api/user';
import { resetRouter } from '../../router/router';

const tokenKey = process.env.VUE_APP_TOKEN_KEY;
const state = {
  name: undefined,
  avatar: undefined,
  roles: null,
};

const mutations = {
  SET_TOKEN(_state, token) {
    setToken(token);
  },
  REMOVE_TOKEN(_state) {
    const backup = _state;
    backup[tokenKey] = undefined;
    removeToken();
  },
  SET_INFO(_state, { name, avatar, roles }) {
    const backup = _state;
    backup.name = name;
    backup.avatar = avatar;
    backup.roles = roles;
  },
  REMOVE_INFO(_state) {
    const backup = _state;
    backup.name = undefined;
    backup.avatar = undefined;
    backup.roles = null;
  },
};

const actions = {
  async login({ commit }, params) {
    try {
      const data = await login(params);
      commit('SET_TOKEN', data.data[tokenKey]);
      return data;
    } catch (err) {
      // 把错误传入调用的地方，处理
      return Promise.reject(err);
    }
  },
  async getInfo({ commit }) {
    try {
      const data = await getInfo();
      commit('SET_INFO', data.data);
      return data;
    } catch (err) {
      console.log(err);
      commit('REMOVE_TOKEN');
      return Promise.reject(err);
    }
  },
  async logout({ commit }) {
    commit('REMOVE_TOKEN');
    commit('REMOVE_INFO');
    resetRouter();
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
